package com.example.ex2.controllers;

import com.example.ex2.mappers.StudentMapper;
import com.example.ex2.pojo.Student;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.*;
import java.util.HashMap;
import java.util.Map;

@Validated
@Controller
public class PersonalInformationController {

    @GetMapping("personalInformation/show")
    public String personalInformationForm(Model model){
        Map map = new HashMap<String,Student>();
        model.addAttribute("Information",studentMapper.show(map));
        return "personalInformation";
    }

    StudentMapper studentMapper = new StudentMapper();

    @RequestMapping("personalInformation/submit")
    public String personalInformationSubmit(@NotNull(message = "姓名 不允许为空")
                                            @Size(min=1,max=20,message = "用户姓名超出范围限制")
                                            @RequestParam(name = "name",required = false) String name,
                                            @NotNull(message = "年级 不允许为空")
                                            @RequestParam(name = "no",required = false) int no,
                                            @Max(2022) @Min(2010)
                                            @RequestParam(name = "grade",required = false) int grade,
                                            @NotBlank(message = "专业 不允许为空")
                                            @RequestParam(name = "major",required = false) String major,
                                            @NotBlank(message = "学院 不允许为空")
                                            @RequestParam(name = "college",required = false) String college,
                                            Model model){

            Map map = new HashMap<String,Student>();
            studentMapper.changeStudent(map,name,no,grade,major,college);
            model.addAttribute("Information",map);
            return "personalInformation";
    }

    @ControllerAdvice
    public class GlobalExceptionHandler {

        @ExceptionHandler(ConstraintViolationException.class)
        @ResponseBody
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        public String handleValidationException(ConstraintViolationException e) {
            for (ConstraintViolation<?> s : e.getConstraintViolations()) {
                return s.getInvalidValue() + "输入错误: " + s.getMessage();
            }
            return "请求参数不合法";
        }
    }

}
